//
//  MyAvailabilityViewController.swift
//  puretennis
//
//  Created by Derek Zheng on 12/1/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class MyAvailabilityViewController: UIViewController {

    
    var timeTabImageView: UIImageView!
    
    var availabilitiesView: UIView = UIView()
    
    var days: [DayAvailabilityImageView] = [];
    
    var startDay = DateUtils.firstDayOfCurrentWeek();
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.titleView = ViewUtils.titleView("时间安排");
        self.showTabBar();
        
        let frameWidth = self.view.frame.width
        
        var description = ViewUtils.label("<     告诉小伙伴你的空余时间段     >", fontSize: 16)
        description.frame.origin = CGPoint(x: (frameWidth - description.frame.width) / 2 , y: ViewUtils.statusBarHeight() + self.navBarHeight()! + 10)
        self.view.addSubview(description)
        
        timeTabImageView = UIImageView(image: UIImage(named: "time_tab"))
        
        
        let originalImageSizeRatio = timeTabImageView.frame.size.height / timeTabImageView.frame.size.width
        
        
        timeTabImageView.frame.size.width = frameWidth * 0.85
        timeTabImageView.frame.size.height = timeTabImageView.frame.size.width * originalImageSizeRatio
        
        timeTabImageView.frame.origin = CGPoint(x: (frameWidth - timeTabImageView.frame.width) / 2 , y: description.frame.origin.y + description.frame.height + 10)
        self.view.addSubview(timeTabImageView)
        
        
        availabilitiesView.frame.origin = CGPoint(x: timeTabImageView.frame.origin.x, y: timeTabImageView.frame.origin.y + timeTabImageView.frame.height)
        Utils.debug(timeTabImageView.frame.origin.x)
        availabilitiesView.userInteractionEnabled = true;
        availabilitiesView.frame.size = CGSize(width: self.view.frame.width, height: self.view.frame.height - availabilitiesView.frame.origin.y);
        
        self.view.addSubview(availabilitiesView);
        
        self.loadAvailabilitiesView();
        
        var swipeGestureLeft =  UISwipeGestureRecognizer(target:self, action:Selector("refreshAvailabilities:"));
        swipeGestureLeft.direction = UISwipeGestureRecognizerDirection.Left;
        self.availabilitiesView.addGestureRecognizer(swipeGestureLeft);
        
        var swipeGestureRight =  UISwipeGestureRecognizer(target:self, action:Selector("refreshAvailabilities:"));
        swipeGestureRight.direction = UISwipeGestureRecognizerDirection.Right;
        self.availabilitiesView.addGestureRecognizer(swipeGestureRight);

    }

    func clearDays(){
        for day in days{
            day.removeFromSuperview();
        }
        
        days = [];
        
    }
    
    func refreshAvailabilities(gesture: UIGestureRecognizer){                
        
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
                TransitionUtils.slideInFromLeft(availabilitiesView);
                self.startDay = DateUtils.plusWeeks(self.startDay, weeks: -1);
                break;
            case UISwipeGestureRecognizerDirection.Left:
                TransitionUtils.slideInFromRight(availabilitiesView);
                self.startDay = DateUtils.plusWeeks(self.startDay, weeks: 1);
                break;
            default:
                break
            }
        }
        loadAvailabilitiesView();
    }
    
    
    func loadAvailabilitiesView(){

        clearDays();
        var screenDimensionRate = self.view.frame.height / self.view.frame.width;
        
        let screenWidth = self.view.frame.width;
        let availabilityView = availabilitiesView.frame.origin;
        
        var lastX:CGFloat = 1;
        var lastY:CGFloat = 8;
        var paddingRow: CGFloat = screenDimensionRate > 1.5 ? 4: 0;
        
        var dateStart = self.startDay;
        for(var i = 0; i < 7; i++){
            var day = DayAvailabilityImageView(date: dateStart, position: CGPoint(x: lastX, y: lastY), width: self.timeTabImageView.frame.width / 4);
            
            renderDay(day);
            lastY += day.frame.height + paddingRow;
            dateStart = DateUtils.plusDays(dateStart, days: 1);
            days.append(day);
            
        }

        var endDay = DateUtils.plusWeeks(self.startDay, weeks: 1);
        var fromText = DateUtils.toString(self.startDay, format: "yyyy-MM-dd");
        var toText = DateUtils.toString(endDay, format: "yyyy-MM-dd");
        var url = "/api/v1/user/availabilities/\(fromText)/\(toText)";
        
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var weeklyAvailabilities = response as NSMutableArray;
            for dailyAvailabilities in weeklyAvailabilities{
                var dictionary = dailyAvailabilities as NSMutableDictionary;
                var date = dictionary.objectForKey("date") as String;
                
                var availabilities = dictionary.objectForKey("availability") as NSMutableDictionary;
                
                for day in self.days{
                    day.resolveAvailability(date, availabilities: availabilities)
                }
            }

            }, errorHandle: { (error) -> Void in
                self.processComplete();
                Utils.debug("Error happens when get availabilities");
        })
        
    }
    
    func renderDay(day: DayAvailabilityImageView){
        self.availabilitiesView.addSubview(day);
        self.availabilitiesView.addSubview(day.morning!);
        self.availabilitiesView.addSubview(day.afternoon!);
        self.availabilitiesView.addSubview(day.evening!);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
